package com.fuang.io.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Date;
import java.util.Iterator;
import java.util.Set;

/**
 * nio处理步骤：
 * 1，新建Selector
 * 2，新建ServerSocketChannel
 * 3，ServerSocketChannel绑定端口
 * 4，ServerSocketChannel注册连接就绪事件到selector
 * 5，当selector返回连接就绪事件后ServerSocketChannel通过accept()接入连接并返回SocketChannel进行socket交互数据，并注册读就绪事件
 * 5，当selector返回读就绪事件后，进行read->handle->write
 * Created by Fuang on 2018-9-19.
 */
public class NioTimeServerHandler implements Runnable {
    private Selector selector;
    private ServerSocketChannel serverSocketChannel;
    private volatile boolean stop;

    /**
     * 初始化多路复用器，绑定监听端口
     * @param port
     */
    public NioTimeServerHandler(int port) {
        try {
            selector = Selector.open();
            serverSocketChannel = ServerSocketChannel.open();
            serverSocketChannel.configureBlocking(false); // 设置非阻塞
            serverSocketChannel.socket().bind(new InetSocketAddress(port), 1024); // 绑定端口
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); // 注册Socket接受请求事件
            System.out.println("The time server is start in port : " + port);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void stop() {
        this.stop = true;
    }

    @Override
    public void run() {
        while (!stop) {
            try {
                selector.select(1000); // 循环获取就绪事件
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> it = selectionKeys.iterator();
                while (it.hasNext()) {
                    SelectionKey selectionKey = it.next();

                    try {
                        handleInput(selectionKey); // 处理就绪事件包括：连接就绪、读就绪、写就绪
                    } finally {
                        if (selectionKey != null) {
                            selectionKey.cancel();
                            if (selectionKey.channel() != null) {
                                selectionKey.channel().close();
                            }
                        }
                    }

                    it.remove();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        if (selector != null) {
            try {
                selector.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void handleInput(SelectionKey selectionKey) throws IOException {
        if (!selectionKey.isValid()) {
            return;
        }

        if (selectionKey.isAcceptable()) { // 处理连接就绪
            ServerSocketChannel serverSocketChannel = (ServerSocketChannel) selectionKey.channel();
            SocketChannel socketChannel = serverSocketChannel.accept(); //
            socketChannel.configureBlocking(false);
            socketChannel.register(selector, SelectionKey.OP_READ); // 注册读就绪事件
        }

        if (selectionKey.isReadable()) { // 处理读就绪
            SocketChannel socketChannel = (SocketChannel) selectionKey.channel();

            // read
            String body = read(socketChannel);

            // handle
            String response = handle(body);

            //wtrie
            write(socketChannel, response);

            // 关闭资源
            selectionKey.cancel();
            socketChannel.close();
        }
    }

    /**
     * 读取socket内容
     * @param socketChannel
     * @return
     * @throws IOException
     */
    private String read(SocketChannel socketChannel) throws IOException {
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        int bytesRead = socketChannel.read(byteBuffer); // 从socketChannel读数据到buffer
        StringBuilder body = new StringBuilder();
        while (bytesRead > 0) {
            byteBuffer.flip(); // buffer从写状态翻转到读状态
            byte[] bytes = new byte[byteBuffer.remaining()];
            byteBuffer.get(bytes);
            body.append( new String(bytes, "UTF-8"));
            byteBuffer.clear();
            bytesRead = socketChannel.read(byteBuffer);
        }
        System.out.println("The time server receive order : " + body);

        return body.toString();
    }

    /**
     * 处理请求
     * @param request
     * @return
     */
    private String handle(String request) {
        return  "QUERY TIME ORDER".equals(request) ? new Date().toString() : "Bad Order";
    }

    /**
     * 返回客户端数据
     * @param socketChannel
     * @param response
     * @throws IOException
     */
    private void write(SocketChannel socketChannel, String response) throws IOException {
        if (response != null && response.trim().length() > 0) {
            byte[] bytes = response.getBytes();
            ByteBuffer byteBuffer = ByteBuffer.allocate(bytes.length);
            byteBuffer.put(bytes);
            byteBuffer.flip();
            socketChannel.write(byteBuffer);
        }
    }
}
